<template>
	<view class="add-record-container">
		<!-- 标题头部 -->
		<view class="page-header">
			<text class="title">添加血糖记录</text>
		</view>
		
		<!-- 血糖值输入卡片 -->
		<view class="glucose-card">
			<text class="glucose-label">血糖值 (mmol/L)</text>
			<view class="glucose-input-area">
				<input
					class="glucose-input"
					type="digit"
					v-model="formData.value"
					@input="valueInput"
					placeholder="0.0"
				/>
				<view class="glucose-status" :class="getValueLevelClass()">
					<text>{{ getValueLevelText() }}</text>
				</view>
			</view>
			<view class="glucose-range">
				<text>参考范围: 3.9-6.1 mmol/L (空腹)</text>
			</view>
		</view>
		
		<view class="form-container">
			<uni-forms ref="recordForm" :model="formData" :rules="rules" label-position="top">
				<!-- 日期时间选择 -->
				<view class="form-section">
					<view class="section-title">
						<t-icon name="calendar" size="18" color="#666"></t-icon>
						<text>测量时间</text>
					</view>
					
					<view class="date-time-row">
						<!-- 日期选择 -->
						<view class="date-picker">
							<uni-datetime-picker 
								type="date" 
								format="yyyy-MM-dd" 
								:clear-icon="false"
								v-model="formData.date"
								@change="dateChange"
								:border="true"
							>
								<view class="picker-trigger">
									<text>{{ formData.date }}</text>
									<t-icon name="chevron-down" size="16" color="#999"></t-icon>
								</view>
							</uni-datetime-picker>
						</view>
						
						<!-- 时间选择 -->
						<view class="time-picker">
							<uni-datetime-picker 
								type="time" 
								format="HH:mm" 
								:clear-icon="false"
								v-model="formData.time" 
								@change="timeChange"
								:border="true"
							>
								<view class="picker-trigger">
									<text>{{ formData.time }}</text>
									<t-icon name="chevron-down" size="16" color="#999"></t-icon>
								</view>
							</uni-datetime-picker>
						</view>
					</view>
				</view>
				
				<!-- 类型选择 -->
				<view class="form-section">
					<view class="section-title">
						<t-icon name="app" size="18" color="#666"></t-icon>
						<text>测量时段</text>
					</view>
					
					<view class="type-group">
						<view 
							class="type-item" 
							v-for="(item, index) in typeOptions" 
							:key="index"
							:class="{ active: formData.type === item.value }"
							@tap="selectType(item.value)"
						>
							<text>{{ item.label }}</text>
						</view>
					</view>
				</view>
				
				<!-- 备注输入 -->
				<view class="form-section">
					<view class="section-title">
						<t-icon name="edit" size="18" color="#666"></t-icon>
						<text>备注</text>
					</view>
					
					<uni-easyinput 
						type="textarea"
						class="remark-input" 
						v-model="formData.remark" 
						placeholder="请输入备注信息（可选）"
						:maxlength="100"
					/>
				</view>
			</uni-forms>
			
			<!-- 按钮组 -->
			<view class="btn-group">
				<button class="btn-cancel" @tap="goBack">取消</button>
				<button class="btn-submit" @tap="submitForm">保存</button>
			</view>
		</view>
	</view>
</template>

<script setup>
	import { ref, reactive, onMounted } from 'vue'
	import { getBloodSugarStore } from '@/common/utils/store-helper.js'
	import { addRecord, getBloodSugarRecords } from '@/common/api/record.js'
	import { getUserInfo } from '@/common/utils/auth.js'
	import dataSyncService from '@/common/services/dataSync.js'
	
	// 成功提交计数
	const successCount = ref(0)
	
	// 使用Pinia状态管理
	const bloodSugarStore = ref(null)
	
	// 表单引用
	const recordForm = ref(null)
	
	// 表单数据
	const formData = reactive({
		date: new Date().toISOString().split('T')[0],  // 格式：YYYY-MM-DD
		time: new Date().toTimeString().substring(0, 5),  // 格式：HH:MM
		value: '',
		type: 'beforeBreakfast',
		remark: ''
	})
	
	// 表单验证规则
	const rules = {
		date: {
			rules: [{
				required: true,
				errorMessage: '请选择日期'
			}]
		},
		time: {
			rules: [{
				required: true,
				errorMessage: '请选择时间'
			}]
		},
		value: {
			rules: [{
				required: true,
				errorMessage: '请输入血糖值'
			}, {
				validateFunction: (rule, value, data, callback) => {
					if (value && (isNaN(value) || parseFloat(value) <= 0 || parseFloat(value) > 30)) {
						callback('请输入有效的血糖值(0-30)');
					}
					return true
				}
			}]
		},
		type: {
			rules: [{
				required: true,
				errorMessage: '请选择记录类型'
			}]
		}
	}
	
	// 记录类型选项
	const typeOptions = [
		{ label: '空腹', value: 'beforeBreakfast' },
		{ label: '早餐后', value: 'afterBreakfast' },
		{ label: '午餐前', value: 'beforeLunch' },
		{ label: '午餐后', value: 'afterLunch' },
		{ label: '晚餐前', value: 'beforeDinner' },
		{ label: '晚餐后', value: 'afterDinner' },
		{ label: '睡前', value: 'beforeSleep' },
		{ label: '随机', value: 'random' }
	]
	
	// 日期变更
	const dateChange = (e) => {
		formData.date = e
	}
	
	// 时间变更
	const timeChange = (e) => {
		formData.time = e
	}
	
	// 血糖值输入
	const valueInput = (e) => {
		// 限制只能输入数字和小数点
		formData.value = e.target.value.replace(/[^\d.]/g, '')
		// 限制只能有一个小数点
		if (formData.value.split('.').length > 2) {
			formData.value = formData.value.replace(/\.+/g, '.')
		}
		// 限制小数点后最多一位
		if (formData.value.indexOf('.') > -1) {
			formData.value = formData.value.substring(0, formData.value.indexOf('.') + 2)
		}
	}
	
	// 选择类型
	const selectType = (type) => {
		formData.type = type
	}
	
	// 返回上一页
	const goBack = () => {
		// 如果是从bloodSugar/index页面跳转来的，则返回到record/list页面
		const pages = getCurrentPages();
		if (pages.length > 1) {
			const prevPage = pages[pages.length - 2];
			if (prevPage.route && prevPage.route.includes('bloodSugar/index')) {
				uni.redirectTo({
					url: '/pages/record/list'
				});
				return;
			}
		}
		
		// 否则正常返回上一页
		uni.navigateBack();
	}
	
	// 获取血糖值等级
	const getValueLevelClass = () => {
		const value = parseFloat(formData.value)
		if (isNaN(value)) return ''
		
		if (value < 3.9) return 'status-low'
		if (value > 7.0) return 'status-high'
		return 'status-normal'
	}
	
	// 获取血糖值状态文本
	const getValueLevelText = () => {
		const value = parseFloat(formData.value)
		if (isNaN(value) || value === 0) return '请输入'
		
		if (value < 3.9) return '偏低'
		if (value > 7.0) return '偏高'
		return '正常'
	}
	
	// 表单验证
	const validateForm = () => {
		return new Promise((resolve, reject) => {
			// 表单项检查
			if (!formData.date) {
				reject('请选择日期');
				return;
			}
			
			if (!formData.time) {
				reject('请选择时间');
				return;
			}
			
			if (!formData.value) {
				reject('请输入血糖值');
				return;
			}
			
			if (isNaN(formData.value) || parseFloat(formData.value) <= 0 || parseFloat(formData.value) > 30) {
				reject('请输入有效的血糖值(0-30)');
				return;
			}
			
			if (!formData.type) {
				reject('请选择记录类型');
				return;
			}
			
			// 所有检查通过
			resolve(true);
		});
	}
	
	// 获取类型文本
	const getTypeText = (type) => {
		const option = typeOptions.find(item => item.value === type)
		return option ? option.label : '未知'
	}
	
	// 添加血糖记录
	const submitRecord = async (record) => {
		try {
			console.log('准备提交血糖记录:', record)
			
			// 显示loading
			showLoading('正在保存...')
			
			// 调用API保存记录
			const res = await addRecord(record)
			
			// 关闭loading
			hideLoading()
			
			if (res.code === 0 || res.code === 200) {
				return {
					success: true,
					data: res.data
				}
			} else {
				throw new Error(res.message || '保存失败')
			}
		} catch (error) {
			// 确保loading已关闭
			hideLoading()
			console.error('保存血糖记录失败:', error)
			throw error
		}
	}
	
	// 提交表单
	const submitForm = async () => {
		try {
			// 表单验证
			await validateForm()
			
			// 获取用户信息 - 使用auth.js中的标准方法
			const userInfo = getUserInfo() || {}
			// 检查是否需要登录
			const token = uni.getStorageSync('xuetang_token')
			
			if (!userInfo.id && !token) {
				// 如果既没有用户ID也没有token，表示未登录
				throw new Error('请先登录后再提交记录')
			}
			
			// 使用用户ID，如果没有则使用默认测试用户ID
			const userId = userInfo.id || 6  // 使用默认测试用户ID 6
			console.log('当前使用的用户ID:', userId)
			
			// 构建前端记录数据
			const frontendRecord = {
				id: new Date().getTime(),
				date: formData.date,
				time: formData.time,
				value: parseFloat(formData.value),
				type: formData.type,
				typeText: getTypeText(formData.type),
				remark: formData.remark,
				userId: userId
			}
			
			// 转换为后端需要的格式
			const backendRecord = convertToBackendFormat(frontendRecord)
			
			console.log('提交的记录数据:', backendRecord)
			// 调用API提交记录
			showLoading('正在保存...')
			const response = await submitRecord(backendRecord)
			hideLoading()
			
			console.log('提交成功:', response)

			// 成功提交后，更新缓存和状态
			dataSyncService.addRecord(frontendRecord)
			successCount.value++
			
			// 显示成功消息
			showSuccess('记录提交成功')
			
			// 重置表单
			resetForm()
			
			// 获取最新的状态判断
			if (formData.value) {
				checkBloodSugarStatus(formData.value, backendRecord.measureType)
			}
			
			// 2秒后返回上一页
			setTimeout(() => {
				uni.navigateBack()
			}, 1500)
			
		} catch (error) {
			hideLoading()
			console.error('提交记录失败:', error)
			
			// 特别处理服务器内部错误
			if (error.statusCode === 500) {
				showError('服务器处理请求时出错，可能是数据结构不匹配。请联系管理员。')
				
				// 尝试保存到本地
				try {
					const frontendRecord = {
						id: new Date().getTime(),
						date: formData.date,
						time: formData.time,
						value: parseFloat(formData.value),
						type: formData.type,
						typeText: getTypeText(formData.type),
						remark: formData.remark,
						userId: getUserInfo()?.id || 6,
						isLocal: true // 标记为本地记录
					}
					
					// 保存到本地
					dataSyncService.addLocalRecord(frontendRecord)
					showInfo('已将记录保存到本地，将在网络恢复后自动同步')
					
					// 重置表单
					resetForm()
					
					// 2秒后返回上一页
					setTimeout(() => {
						uni.navigateBack()
					}, 1500)
				} catch (localError) {
					console.error('保存到本地失败:', localError)
					showError('保存记录失败，请稍后重试')
				}
			} else {
				// 其他错误处理
				const errorMsg = error.message || '提交记录失败，请稍后重试'
				showError(errorMsg)
			}
		}
	}
	
	/**
	 * 将前端记录格式转换为后端所需格式
	 * @param {Object} frontendRecord - 前端记录对象
	 * @returns {Object} - 后端所需的记录格式
	 */
	const convertToBackendFormat = (frontendRecord) => {
		// 将type转换为measureType的数值
		const measureTypeMap = {
			'beforeBreakfast': 1, // 空腹
			'afterBreakfast': 3, // 餐后1小时
			'beforeLunch': 2, // 餐前
			'afterLunch': 3, // 餐后1小时
			'beforeDinner': 2, // 餐前
			'afterDinner': 3, // 餐后1小时
			'beforeSleep': 5, // 睡前
			'random': 7 // 随机
		}
		
		// 合并日期和时间，注意格式必须与后端接收的格式一致
		const dateTime = `${frontendRecord.date}T${frontendRecord.time}:00`;
		
		// 构建符合后端数据库字段结构的数据
		// 严格按照数据库表结构，不包含unit、meal和status字段
		return {
			userId: frontendRecord.userId || 1, // 用户ID
			value: parseFloat(frontendRecord.value), // 血糖值
			measureTime: dateTime, // 测量时间
			measureType: measureTypeMap[frontendRecord.type] || 1, // 测量类型
			remark: frontendRecord.remark || '' // 备注
		}
	}
	
	// 在组件挂载时初始化store
	const initStore = () => {
		try {
			const store = getBloodSugarStore()
			if (store) {
				bloodSugarStore.value = store
			}
		} catch (error) {
			console.error('初始化store失败:', error)
		}
	}
	
	// 初始化页面
	onMounted(() => {
		// 添加调试日志，检查typeOptions
		console.log('typeOptions:', typeOptions)
		console.log('当前选中类型:', formData.type)
		
		// 确保route存在
		if (typeof __route__ === 'undefined') {
			try {
				const pages = getCurrentPages();
				const currentPage = pages[pages.length - 1];
				// @ts-ignore
				global.__route__ = currentPage.route;
			} catch (e) {
				console.error('获取当前页面路径失败:', e);
				// @ts-ignore
				global.__route__ = '/pages/record/add';
			}
		}
		
		// 初始化时间为当前时间
		const now = new Date();
		formData.date = now.toISOString().split('T')[0];
		
		// 格式化时间为HH:MM
		const hours = now.getHours().toString().padStart(2, '0');
		const minutes = now.getMinutes().toString().padStart(2, '0');
		formData.time = `${hours}:${minutes}`;
		
		// 确保type有初始值
		if (!formData.type) {
			formData.type = 'beforeBreakfast';
		}
		
		// 不再立即初始化store，而是在需要时才调用
		// initStore();
	});
	
	// 辅助函数 - 显示加载提示
	const showLoading = (title) => {
		uni.showLoading({
			title: title || '加载中...',
			mask: true
		})
	}
	
	// 辅助函数 - 隐藏加载提示
	const hideLoading = () => {
		uni.hideLoading()
	}
	
	// 辅助函数 - 显示成功提示
	const showSuccess = (message) => {
		uni.showToast({
			title: message,
			icon: 'success'
		})
	}
	
	// 辅助函数 - 显示错误提示
	const showError = (message) => {
		uni.showToast({
			title: message,
			icon: 'none'
		})
	}
	
	// 辅助函数 - 显示普通信息提示
	const showInfo = (message) => {
		uni.showToast({
			title: message,
			icon: 'none'
		})
	}
	
	// 检查血糖状态并提供反馈
	const checkBloodSugarStatus = (value, measureType) => {
		// 血糖值范围检查
		const val = parseFloat(value)
		if (isNaN(val)) return
		
		// 根据测量类型确定正常范围
		let lowerLimit = 3.9
		let upperLimit = 6.1
		
		switch (measureType) {
			case 1: // 空腹
				lowerLimit = 3.9
				upperLimit = 6.1
				break
			case 2: // 餐前
				lowerLimit = 3.9
				upperLimit = 6.1
				break
			case 3: // 餐后1小时
				lowerLimit = 3.9
				upperLimit = 10.0
				break
			case 4: // 餐后2小时
				lowerLimit = 3.9
				upperLimit = 7.8
				break
			case 5: // 睡前
				lowerLimit = 3.9
				upperLimit = 7.0
				break
			default:
				lowerLimit = 3.9
				upperLimit = 7.8
		}
		
		// 根据血糖值提供反馈
		if (val < lowerLimit) {
			showInfo('您的血糖偏低，请注意补充适量碳水')
		} else if (val > upperLimit) {
			showInfo('您的血糖偏高，请控制饮食并适当运动')
		} else {
			showSuccess('血糖处于正常范围，请继续保持')
		}
	}
	
	// 重置表单
	const resetForm = () => {
		// 重置为默认值
		const now = new Date()
		formData.date = now.toISOString().split('T')[0]
		
		// 格式化时间为HH:MM
		const hours = now.getHours().toString().padStart(2, '0')
		const minutes = now.getMinutes().toString().padStart(2, '0')
		formData.time = `${hours}:${minutes}`
		
		// 重置其他字段
		formData.value = ''
		formData.type = 'beforeBreakfast'
		formData.remark = ''
		
		// 重置表单验证状态
		if (recordForm.value) {
			recordForm.value.resetFields()
		}
	}
</script>

<style lang="scss">
	.add-record-container {
		min-height: 100vh;
		background-color: #f5f7fa;
		padding-bottom: 40rpx;
		
		.page-header {
			background-color: #8cc9a1;
			padding: 30rpx;
			padding-top: 60rpx;
			
			.title {
				color: #fff;
				font-size: 38rpx;
				font-weight: 600;
			}
		}
		
		.glucose-card {
			background: linear-gradient(135deg, #8cc9a1 0%, #6eb888 100%);
			margin: 30rpx;
			border-radius: 16rpx;
			padding: 30rpx;
			color: #fff;
			box-shadow: 0 4rpx 10rpx rgba(0, 0, 0, 0.1);
			
			.glucose-label {
				font-size: 28rpx;
				opacity: 0.9;
			}
			
			.glucose-input-area {
				display: flex;
				align-items: center;
				justify-content: space-between;
				margin: 20rpx 0;
				
				.glucose-input {
					font-size: 60rpx;
					font-weight: bold;
					width: 60%;
					height: 100rpx;
					color: #fff;
				}
				
				.glucose-status {
					font-size: 32rpx;
					padding: 10rpx 30rpx;
					background: rgba(255, 255, 255, 0.3);
					border-radius: 30rpx;
					
					&.status-normal {
						background: rgba(255, 255, 255, 0.3);
					}
					
					&.status-high {
						background: rgba(240, 90, 90, 0.7);
					}
					
					&.status-low {
						background: rgba(90, 140, 240, 0.7);
					}
				}
			}
			
			.glucose-range {
				font-size: 24rpx;
				opacity: 0.8;
			}
		}
		
		.form-container {
			margin: 30rpx;
			
			.form-section {
				background-color: #ffffff;
				border-radius: 16rpx;
				padding: 30rpx;
				margin-bottom: 30rpx;
				box-shadow: 0 2rpx 8rpx rgba(0, 0, 0, 0.05);
				
				.section-title {
					display: flex;
					align-items: center;
					margin-bottom: 20rpx;
					
					text {
						margin-left: 12rpx;
						font-size: 32rpx;
						color: #333;
						font-weight: 500;
					}
				}
				
				.date-time-row {
					display: flex;
					
					.date-picker {
						flex: 3;
						margin-right: 20rpx;
					}
					
					.time-picker {
						flex: 2;
					}

					.picker-trigger {
						display: flex;
						align-items: center;
						justify-content: space-between;
						height: 80rpx;
						padding: 0 20rpx;
						background-color: #f0f2f5;
						border-radius: 12rpx;
						
						text {
							font-size: 28rpx;
							color: #333;
						}
					}
				}
				
				.type-group {
					display: flex;
					flex-wrap: wrap;
					margin: 0 -10rpx;
					
					.type-item {
						width: calc(25% - 20rpx);
						margin: 10rpx;
						height: 80rpx;
						background-color: #f0f2f5;
						border-radius: 12rpx;
						display: flex;
						align-items: center;
						justify-content: center;
						
						text {
							font-size: 28rpx;
							color: #666;
						}
						
						&.active {
							background-color: #8cc9a1;
							
							text {
								color: #fff;
								font-weight: 500;
							}
						}
					}
				}
				
				.remark-input {
					background-color: #f0f2f5;
					border-radius: 12rpx;
					height: 180rpx;
				}
			}
			
			.btn-group {
				display: flex;
				margin-top: 40rpx;
				
				.btn-cancel, .btn-submit {
					flex: 1;
					height: 90rpx;
					line-height: 90rpx;
					text-align: center;
					border-radius: 45rpx;
					font-size: 32rpx;
				}
				
				.btn-cancel {
					background-color: #f0f2f5;
					color: #666;
					margin-right: 20rpx;
				}
				
				.btn-submit {
					background: linear-gradient(135deg, #8cc9a1 0%, #6eb888 100%);
					color: #fff;
					box-shadow: 0 4rpx 10rpx rgba(110, 184, 136, 0.3);
				}
			}
		}
	}
</style> 